#include "dianewserver.h"
#include "qmessagebox.h"
#include "ui_dianewserver.h"

#include <QUuid>

DiaNewServer::DiaNewServer(QWidget *parent, ModelServer* info) :
    QDialog(parent),
    ui(new Ui::DiaNewServer)
{
    ui->setupUi(this);

    if(info == nullptr)
    {
        this->m_isnew = true;
    }
    else
    {
        this->m_isnew = false;
        this->m_server = info;
        ui->txtName->setText(this->m_server->serverName);
        ui->txtServer->setText(this->m_server->serverDest);
        ui->txtPort->setText(QString::number(this->m_server->serverPort));
        ui->txtUsername->setText(this->m_server->userName);
        ui->txtPasswd->setText(this->m_server->passWd);
    }
}

DiaNewServer::~DiaNewServer()
{
    delete ui;
}

void DiaNewServer::setName(QString name)
{
    ui->txtName->setText(name);
}

void DiaNewServer::setServer(QString dest)
{
    ui->txtServer->setText(dest);
}

void DiaNewServer::setPort(QString port)
{
    ui->txtPort->setText(port);
}

void DiaNewServer::accept()
{
    try {
        QString name=ui->txtName->text();
        QString server=ui->txtServer->text();
        QString sport=ui->txtPort->text();
        QString uname = ui->txtUsername->text();
        QString passwd = ui->txtPasswd->text();

        //校验
        if(name.isNull() || name.isEmpty())
            throw tr("请输入名称~");
        if(server.isNull() || server.isNull())
            throw tr("请输入服务器地址~");
        if(sport.isNull() || sport.isEmpty())
            throw tr("请输入端口号~");

        name = name.trimmed();
        server = server.trimmed();
        sport = sport.trimmed();

        if(uname.isNull() ==false && uname.isEmpty() == false)
            uname = uname.trimmed();
        if(passwd.isNull() == false && passwd.isNull() == false)
            passwd = passwd.trimmed();

        //验证端口号是否合法
        bool ok = false;
        int port = sport.toInt(&ok);

        if(!ok)
            throw tr("无效的数字~");

        if(ok){
            if(port<=0 || port>65536)
                throw tr("无效的端口号~");

            ModelServer info;
            if(this->m_isnew)
            {
                info = ModelServer(QUuid::createUuid().toString(QUuid::WithoutBraces), name.trimmed(), server.trimmed(), port,
                                   uname, passwd);
            }
            else
            {
                info = ModelServer(this->m_server->id, name.trimmed(), server.trimmed(), port,
                                   uname, passwd);
            }

            emit this->signalAccepted(this->m_isnew, info);
            return QDialog::accept();
        }
    } catch (QString ex) {
        QMessageBox::critical(this,tr("提示"),ex);
    }
}

